<template>
  <div class="settings-page">
    <div class="settings-content">
      <!-- 基本信息设置 -->
      <div class="settings-section">
        <h3>基本信息</h3>
        <el-form :model="profileForm" :rules="profileRules" ref="profileFormRef" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="profileForm.username" placeholder="请输入用户名" />
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="profileForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="profileForm.phone" placeholder="请输入手机号" />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="saveProfile" :loading="saving">
              保存基本信息
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 密码修改 -->
      <div class="settings-section">
        <h3>修改密码</h3>
        <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px">
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input v-model="passwordForm.currentPassword" type="password" placeholder="请输入当前密码" show-password />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="passwordForm.newPassword" type="password" placeholder="请输入新密码" show-password />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="passwordForm.confirmPassword" type="password" placeholder="请再次输入新密码" show-password />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="changePassword" :loading="changingPassword">
              修改密码
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 账号安全 -->
      <div class="settings-section danger-section">
        <h3>账号安全</h3>
        <div class="security-item">
          <div class="security-info">
            <h4>注销账号</h4>
            <p>注销后所有数据将被永久删除，此操作不可恢复</p>
          </div>
          <el-button type="danger" @click="deleteAccount">
            注销账号
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'UserSettings',
  setup() {
    const store = useStore()
    const router = useRouter()
    
    const saving = ref(false)
    const changingPassword = ref(false)
    const profileFormRef = ref()
    const passwordFormRef = ref()
    
    const profileForm = reactive({
      username: '',
      email: '',
      phone: ''
    })
    
    const passwordForm = reactive({
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
    
    const profileRules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { pattern: /^[0-9]{11}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
      ]
    }
    
    const passwordRules = {
      currentPassword: [
        { required: true, message: '请输入当前密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }
    
    // 计算属性
    const userInfo = computed(() => store.getters.getUserInfo)
    
    // 方法
    const loadUserInfo = () => {
      if (userInfo.value) {
        profileForm.username = userInfo.value.username || ''
        profileForm.email = userInfo.value.email || ''
        profileForm.phone = userInfo.value.phone || ''
      }
    }
    
    // 获取用户信息
    const fetchUserInfo = async () => {
      try {
        await store.dispatch('fetchUserProfile')
        loadUserInfo()
      } catch (error) {
        // 获取用户信息失败日志已移除
      }
    }
    
    const saveProfile = async () => {
      try {
        await profileFormRef.value.validate()
        saving.value = true
        
        // 这里应该调用API保存
        // await request.put('/user/profile', profileForm)
        
        // 暂时更新本地状态
        store.commit('UPDATE_USER_INFO', {
          ...userInfo.value,
          username: profileForm.username,
          email: profileForm.email,
          phone: profileForm.phone
        })
        
        ElMessage.success('保存成功')
      } catch (error) {
        // 保存失败日志已移除
        ElMessage.error('保存失败，请稍后重试')
      } finally {
        saving.value = false
      }
    }
    
    const changePassword = async () => {
      try {
        await passwordFormRef.value.validate()
        changingPassword.value = true
        
        // 这里应该调用API修改密码
        // await request.put('/user/password', passwordForm)
        
        ElMessage.success('密码修改成功')
        
        // 清空表单
        passwordForm.currentPassword = ''
        passwordForm.newPassword = ''
        passwordForm.confirmPassword = ''
      } catch (error) {
        // 修改密码失败日志已移除
        ElMessage.error('修改密码失败，请稍后重试')
      } finally {
        changingPassword.value = false
      }
    }
    
    const deleteAccount = async () => {
      try {
        await ElMessageBox.confirm(
          '确定要注销账号吗？此操作不可恢复，所有数据将被永久删除。',
          '注销账号',
          {
            confirmButtonText: '确定注销',
            cancelButtonText: '取消',
            type: 'error',
            dangerouslyUseHTMLString: true
          }
        )
        
        // 二次确认
        await ElMessageBox.prompt(
          '请输入 "确认注销" 来确认此操作',
          '最终确认',
          {
            confirmButtonText: '注销账号',
            cancelButtonText: '取消',
            inputPattern: /^确认注销$/,
            inputErrorMessage: '请输入 "确认注销"'
          }
        )
        
        // 这里应该调用API注销账号
        // await request.delete('/user/account')
        
        ElMessage.success('账号已注销')
        store.dispatch('logout')
        router.push('/')
      } catch (error) {
        if (error !== 'cancel') {
          // 注销账号失败日志已移除
          ElMessage.error('注销失败，请稍后重试')
        }
      }
    }
    
    // 页面加载时获取用户信息
    onMounted(() => {
      fetchUserInfo()
    })
    
    return {
      saving,
      changingPassword,
      profileForm,
      passwordForm,
      profileFormRef,
      passwordFormRef,
      profileRules,
      passwordRules,
      saveProfile,
      changePassword,
      deleteAccount
    }
  }
}
</script>

<style scoped>
.settings-page {
  padding: 24px;
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.settings-section {
  background: #f8f9ff;
  border-radius: 12px;
  padding: 24px;
  border: 1px solid #e4e7ed;
}

.settings-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #303133;
  border-bottom: 1px solid #e4e7ed;
  padding-bottom: 12px;
}

.danger-section {
  border-color: #fde2e2;
  background: #fef5f5;
}

.danger-section h3 {
  color: #f56565;
  border-bottom-color: #fde2e2;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-info h4 {
  margin: 0 0 4px 0;
  font-size: 16px;
  color: #303133;
}

.security-info p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

/* 快捷操作样式已移除 */

/* 响应式设计 */
@media (max-width: 768px) {
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style> 